package gc3d.servlet;

import java.io.IOException;
import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * This is an example servlet
 * 
 * @author Bart Kienhuis
 */

public class GC3DDatabaseServlet extends HttpServlet {

	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;

	/** Example of doGet Method implementation */
	public void doGet(HttpServletRequest req, HttpServletResponse response)
			throws ServletException, IOException {
		response.setContentType("text/html");

		PrintWriter out = response.getWriter();
		out.println("<html>");
		out.println("<body>");
		out.println("<head>");
		out.println("<title>Test Database Connection</title>");
		out.println("</head>");
		out.println("<body>");
		out.println("<h1>Test Database Connection</h1>");

		try {
			Class.forName("org.hsqldb.jdbcDriver");
			out.println(" <br> HSQL Database is found");
		} catch (ClassNotFoundException e) {
			out
					.println(" HSQL Database cannot be found. Is hsqldb.jar in WEB-INF/lib ?");
		}

		String url = "jdbc:hsqldb:hsql://localhost/xdb";
		out.println(" <br> Opening database: " + url);

		Connection connection;
		try {
			connection = DriverManager.getConnection(url, "sa", "");
			out.println(" <br> Database opened");

			Statement statement = connection.createStatement();
			ResultSet queryResult = statement
					.executeQuery("select * from name");

			out.println("<br>");
			while (queryResult.next()) {
				out.println("<br>Entry: " + queryResult.getString("name"));
			}
		} catch (SQLException e) {
			out.println(" <br> Database *NOT* opened, is it online?");
			// e.printStackTrace();
		}

		out.println("</body>");
		out.println("</html>");
		out.close();

	}

	/**
	 * Je kan aan elke servlet opvragen welke inhoud hij heeft, en dat wordt
	 * terug gegeven door deze functie:
	 */
	public String getServletInfo() {
		return "Example Database Servlet";
	}
}
